    //
    //  CommonWebViewController.m
    //  EnglishTalk
    //
    //  Created by apple on 15/5/20.
    //  Copyright (c) 2015年 ishowtalk. All rights reserved.
    //

#import "SRCommonWebViewController.h"
#import "FZRemoteNotificationParser.h"

#import "Masonry.h"
#import "FZJSExportObject.h"
#import "FZCommonShareView.h"
#import "FZCommonShare.h"
#import "FZNativeObject.h"

#import "MJRefresh.h"
#import "SRLoginManager.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "SRCommonConstants.h"

@interface SRCommonWebViewController ()<UIWebViewDelegate, FZJSExportCallBackDelegate, NJKWebViewProgressDelegate, FZRemoteNotificationParserDelegate>
{
    
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}

@property (strong, nonatomic, readwrite) UIWebView *webView;
@property (strong, nonatomic) UIButton *shareButton;
@property (strong, nonatomic) UIImageView *shareImageView;

@property(assign, nonatomic) BOOL needBackRefresh;//需要返回到该页面时刷新

@end

@implementation SRCommonWebViewController

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FZJSExportCallBackMethodNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"bindSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"webviewDoback" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"needRefresh" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Refresh" object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRUserLoginDidSuccessNotification object:nil];
    
}


-(instancetype)initControllerWithRemoteNotificationParameters:(NSDictionary *)parameters{
    self = [super initControllerWithRemoteNotificationParameters:parameters];
    if(self){
        self.urlString = [NSString stringWithFormat:@"%@", [parameters objectForKey:@"url"]];
        self.titleStr = @"趣点读";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    if(!self.title || [self.title isEqualToString:@""]){
        self.title = self.titleStr;
    }
    
//    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nativeCallJS:) name: @"FZJSExportCallBackMethodNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(webViewWillReLoad) name: @"bindSuccess" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doBack) name: @"webviewDoback" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(webViewWillReLoad) name: @"needRefresh" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadWebview) name: @"Refresh" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLoginSuccessNotification:) name:SRUserLoginDidSuccessNotification object:nil];

    
    [self createWebView];
    NSString *userAgent = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *version = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    NSString *customUserAgent = [userAgent stringByAppendingFormat:@"/APP-VERSION=%@",version];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent}];
    
    
    if(self.needClose){
        UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
            //        [rightBarButton setBackgroundImage:[UIImage  imageNamed:@"common_add"] forState:UIControlStateNormal];
        [rightBarButton setTitle:@"关闭" forState:UIControlStateNormal];
        [rightBarButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        rightBarButton.titleLabel.font = [UIFont systemFontOfSize:16];
            //        rightBarButton.titleLabel.textColor = [UIColor blackColor];
        rightBarButton.frame = CGRectMake(0, 0, 44, 44);
        [rightBarButton addTarget: self action: @selector(close) forControlEvents: UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarButton];
        [self setRightBarButtonItem:rightBarButtonItem];
    }
    if (self.needShare && !self.shareImage) {
        WEAKSELF
        [self.shareImageView sd_setImageWithURL:[NSURL URLWithString:self.shareImageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
            if(image && !error && weakSelf){
                weakSelf.shareImage = image;
            }
        }];
    }
    
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:_progressView];
    
    if (self.needBackRefresh) {
        [self reloadWebview];
    }
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [_progressView removeFromSuperview];
//    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

-(void)doBack{
    if(!self.needGoBack){
        [super doBack];
    }else{
        if([self.webView canGoBack]){
            if(!self.needShare){
                self.shareButton.hidden = YES;
            }
            [self.webView goBack];
        }else{
            if (self.isPeiyinTalk) {
                self.tabBarController.selectedIndex = 0;
//                AppDelegate *appdelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
//                [appdelegate.navigationController popToRootViewControllerAnimated:NO];
//                [appdelegate.navigationController2 popToRootViewControllerAnimated:NO];
//                [appdelegate.navigationController3 popToRootViewControllerAnimated:NO];
//                [appdelegate.navigationController4 popToRootViewControllerAnimated:NO];
//                [appdelegate.navigationController5 popToRootViewControllerAnimated:NO];
                return;
            }
            [super doBack];
        }
    }
}

-(void)close{
    [super doBack];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)createWebView
{
    UIWebView *webView = [[UIWebView  alloc] initWithFrame:self.view.bounds];
    webView.backgroundColor=[UIColor whiteColor];
    webView.delegate =self;
    self.webView = webView;
    [self.view addSubview:webView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.webView.allowsInlineMediaPlayback = YES;
    
//    NSURL *url = [NSURL URLWithString:self.urlString];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    
//    [webView loadRequest:request];
    if (self.urlString && ![self.urlString isEqualToString:@""]) {
        NSURL *url = [NSURL URLWithString:self.urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];
    } else {
        [webView loadHTMLString:self.htmlString baseURL:nil];
    }
    
    UIBarButtonItem *itemSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    itemSpacer.width = -10;
    self.shareButton= [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shareButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.shareButton.frame = CGRectMake(0, 0, 44, 44/2);
    [self.shareButton setImage:[UIImage imageNamed:@"my_share"] forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareWeb) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.shareButton];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:itemSpacer, rightItem, nil];
    
    self.shareImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    if(!self.needShare){
        self.shareButton.hidden = YES;
    }
    
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _progressView.progressBarView.backgroundColor = [FZStyleSheet currentStyleSheet].color_1;
}

-(void)shareWeb{
    WEAKSELF
    FZCommonShareContent *shareContent = [[FZCommonShareContent alloc] init];
    shareContent.dataType = FZCommonShareContentTypeWebpage;
    shareContent.title = self.shareTitle;
    shareContent.desc = self.shareMessage;
    shareContent.thumbnailData = UIImagePNGRepresentation(self.shareImage);
    shareContent.webpageUrl = self.shareUrl;
    
    [[FZCommonShare sharedInstance] shareFromViewController:self content:shareContent fullCompletion:^(FZCommonShareSocialSNSType socialType, FZCommonShareResponseState responseState, NSString *errorMessage) {
        if (responseState == FZCommonShareResponseStateSuccess) {
            [weakSelf showHUDHintWithText:@"分享成功"];
        } else if (responseState == FZCommonShareResponseStateNotInstalled) {
            [weakSelf showHUDHintWithText:[NSString stringWithFormat:@"您的手机不支持分享到该APP"]];
        }
    }];
}
# pragma natification  handle JS needs

-(void)webViewWillReLoad
{
    WEAKSELF
    [self.webView.scrollView addLegendHeaderWithRefreshingBlock:^{
        
        [weakSelf.webView reload];
        [weakSelf.webView.scrollView.header endRefreshing];
        
    }];
}
-(void)reloadWebview {
    [self.webView reload];
}


- (void)userDidLoginSuccessNotification:(NSNotification *)notification {
//    [self reloadWebview];
}

#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *requestPath = [[request URL] absoluteString];
    self.urlString=requestPath;
    if ([requestPath hasPrefix:@"enlishtalk://"]) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:requestPath]];
    }
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
        //网页加载完成调用此方法
    
    [self.webView.scrollView.header setHidden:YES];//处理刷新
    
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    FZJSExportObject *fZJSExportObject=[FZJSExportObject new];
    fZJSExportObject.callBackDelegate = self;
    context[@"fZJSExportObject"]=fZJSExportObject;
    
    self.title=[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];//获取h5的title
        //    self.shareTitle=[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];//获取分享的title
    self.shareUrl = [self.webView stringByEvaluatingJavaScriptFromString:@"document.URL"];
    
//    [self.loadingView hide];

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
        //加载失败
}
-(void)nativeCallJS:(NSNotification*)notion
{
    
    NSString*string= [FZNativeObject getJSONStringFromNative];
    NSString*userInfo=[NSString stringWithFormat:@"nativeCallJs('%@')",string];
    JSContext *context=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [context evaluateScript:userInfo];
    
}

#pragma mark FZJSExportCallBackDelegate
-(void)jsCallback:(NSInteger)action params:(NSDictionary *)params{
//    NSLog(@"*****jsCallback params:%@-- %d", params, action);

    NSString *backRefresh = params[@"backRefresh"];
    if (backRefresh) {
        self.needBackRefresh = [backRefresh integerValue];
    }
    
    WEAKSELF
    if(action == 3){
            //controller跳转
            // 跳转专辑界面，目前只有配音大赛才会跳转专辑，后期对配音大赛的判断要修改
//        dispatch_async(dispatch_get_main_queue(), ^{
//            FZSpecialViewController *specialController = [[FZSpecialViewController alloc] init];
//            specialController.album_id = [NSString stringWithFormat:@"%@", [params objectForKey:@"albumId"]];
//            specialController.isPeiyinTalk = YES;
//            [weakSelf.navigationController pushViewController:specialController animated:YES];
//            
//        });
        
    }
    else if(action == 5){
            //分享处理
            //{\"action\":5,\"app_share\":1,\"title\":\"分享测试\",\"desc\":"分享描述",\"pic\":\"http:\/\/7u2nh5.com2.z0.glb.qiniucdn.com\/1020149182.jpg\",\"url\":"http:\/\/www.baidu.com"'}
            //app_share 为1里 webView右上角显示分享按钮  为0时 弹出分享界面
        WEAKSELF
        NSString *picUrl = [params objectForKey:@"pic"];
        [self.shareImageView sd_setImageWithURL:[NSURL URLWithString:picUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
            if(image && !error && weakSelf){
                weakSelf.shareImage = image;
            }
        }];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.shareTitle = [params objectForKey:@"title"];
            self.shareMessage = [params objectForKey:@"desc"];
            self.shareUrl = [params objectForKey:@"url"];
            self.shareImage = _shareImage ? self.shareImage:[UIImage imageNamed:@"AppIcon"];
            
//            NSLog(@"**********[params objectForKey:app_share:%@", [params objectForKey:@"app_share"]);
            if([params objectForKey:@"app_share"] && [[params objectForKey:@"app_share"] integerValue] == 1){
                self.shareButton.hidden = NO;
//                NSLog(@"**********[params objectForKey:app_share: show");

            }else{
//                NSLog(@"**********[params objectForKey:app_share: hidden");
                [self shareWeb];
                self.shareButton.hidden = YES;
            }
            //先下载需要的图片
            
        });
    } else if (action == 6) {
            //跳转到登录注册页面
//        [[SRLoginManager sharedManager] showLoginViewSinceController:self];
    } else if (action == 7) {
        [self doBack];
    }
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
//    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

- (void)controlPushView: (SRCommonViewController *)object {
//    if (![[SRLoginManager sharedManager] hasLogin]) {
//        [[SRLoginManager sharedManager] showLoginViewSinceController:self];
//    } else {
        [self.navigationController pushViewController:object animated:YES];
//    }
}


@end
